package com.example.qqfake;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

public class FindresultActivity extends AppCompatActivity {
    private final String serverAddress = "192.168.104.215";
    private final int serverPort = 50000;

    public Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    private Button exit;
    private EditText search;
    private Button queding;
    private TextView show_name;
    private TextView show_id;

    private String myid;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_findresult);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        // 获取SharedPreferences实例，文件名为"myPreferences"，与MainActivity中使用的文件名相同
        SharedPreferences sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
        // 读取数据，键为"User_id"
        myid = sharedPreferences.getString("User_id","hhh");


        exit = findViewById(R.id.exit_button);
        search = findViewById(R.id.search_View);
        queding = findViewById(R.id.search_Button);
        show_id = findViewById(R.id.find_show_id);
        show_name=findViewById(R.id.find_show_name);






        //回到联系人界面
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FindresultActivity.this,FriendActivity.class);
                startActivity(intent);
                System.exit(0);
            }
        });

        //搜索按钮
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(search.getText().toString().equals(" ")){
                    Toast.makeText(FindresultActivity.this,"请输入id号",Toast.LENGTH_LONG).show();
                }else{
                    searchUsers(search.getText().toString());

                }
            }
        });
        show_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAddContactDialog(show_id.getText().toString());

            }
        });





        //子线程开启socket发送连接请求，不停监听信息
        new Thread(()->{
            try {

                socket= new Socket(serverAddress, serverPort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out= new PrintWriter(socket.getOutputStream(), true);

                // 启动读取消息的线程
                new Thread(this::readMessages).start();
                /*
                 * 由FindresultActivity发送的消息：
                 *
                 * 1.搜索用户消息，当用户输入搜索用户的id，点击搜索，将id传给服务器，若未找到，返回false5，弹窗提示用户不存在
                 *              若存在该用户，返回他的用户名和id，将其显示在show_name,show_id
                 * 2.添加好友信息，当用户点击搜索结果的show_name,发送请求 ：myid+“ ”+goal_id
                 *               若两人已经是好友，服务器返回false3,弹窗提示好友已经添加
                 *               添加成功，直接跳转联系人页面（重新加载联系人页面），可以看到添加的结果
                 *
                 *
                 * */

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }).start();



    }


    private void searchUsers(String query) {
        //子线程发送搜索消息
        Date now = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedString = formatter.format(now);
        String message = "6,"+"6"+","+formattedString+","+query+","+"6";
        Thread thread = new Thread(new Worker(message));
        thread.start();
        search.setText("");

    }


    //添加联系人确认框
    private void showAddContactDialog(String id1) {
        //已经存在的联系人
        new AlertDialog.Builder(this)
                .setTitle("添加联系人")
                .setMessage("是否将 " + id1 + " 添加为联系人？")
                .setPositiveButton("确定", (dialog, which) -> {
                    addNewContact(id1);

                })
                .setNegativeButton("取消", null)
                .show();
    }
    private void addNewContact(String id1){
        //子线程开启socket
        //子线程发送搜索消息
        Date now = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedString = formatter.format(now);
        String message = "3,"+myid+","+formattedString+","+myid+" "+id1+","+myid;

        Thread thread = new Thread(new Worker(message));
        thread.start();


    }


    private void readMessages() {
        try {
            String message;
            while ((message = in.readLine()) != null) {
                if(message.equals("false5")){
                    //查找用户失败，弹窗提示用户不存在
                    if(!isFinishing()){
                        Log.v("msg","none");
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @Override
                            public void run() {
                                Toast.makeText(FindresultActivity.this, "未找到用户", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }else if(message.equals("false3")){
                    //添加好友失败，弹窗提示
                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @Override
                            public void run() {
                                Log.v("msg","friend");
                                Toast.makeText(FindresultActivity.this, "好友已添加", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }else if(message.equals("true")){
                    //添加好友成功，跳转画面
                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @Override
                            public void run() {
                                Toast.makeText(FindresultActivity.this, "添加联系人成功", Toast.LENGTH_SHORT).show();
                                Intent intent =new Intent(FindresultActivity.this,FriendActivity.class);
                                startActivity(intent);
                                System.exit(0);
                            }
                        });
                    }

                }else{
                    String[] parts = message.split(" ");
                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @Override
                            public void run() {
                                //给show_ia ,show_name,setText
                                show_name.setText(parts[1]);
                                show_id.setText(parts[0]);
                            }
                        });
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public class Worker implements Runnable {
        private String message;
        public Worker(String message) {
            this.message = message;
        }
        @Override
        public void run() {
            // 使用传递的消息
            out.println(message);
        }
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
        try{
            //关闭输入流，socket连接

            if(socket!=null){
                socket.close();
                in.close();
                out.close();
            }
        }catch(IOException e){
            e.printStackTrace();

        }

    }



}